<!--
* description: 采购索赔申请
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <!-- <el-row style="background-color:#fff;padding-top:1rem">
      <el-col :span="2" :offset="22"><span style="cursor:pointer" @click="togglestatus()">备件状态:</span><i :class="icon" /></el-col>
    </el-row> -->
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :edit-row-data="editRowData1"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/paSparePartsManagement'
import {exportExcel} from "@/utils/exportExcel";

import Vue from 'vue'
import api from "@/views/pa/financialManagement/sparePartsBonusOperation/api";

export default {
  name: 'PurchaseApplicationClaim',

  components: {
    OneTableTemplate,
    Edit: () => import('./claimApplicationMaking')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      icon: 'el-icon-arrow-down',
      status: false,
      editRowData1: {},
      editPopupsState: '',
      selectiondata: null,
      // 网格查询API配置对象
      apiConfig: orgApis.purchaseApplicationClaimQuery,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '索赔类型：',
              codeField: 'claimOrderType',
              component: () => import('@/components/org/commonSelect'),
              // oFields: "statusId,statusText",

              // options: [
              //   { statusId: "0", statusText: "货差索赔" },
              //   { statusId: "1", statusText: "货损索赔" },
              //   { statusId: "2", statusText: "物流索赔" },
              // ],
              customObj: {
                api: orgApis.purchaseApplicationClaimClaimType
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true

            },
            {
              // compKey: "compKey2",
              labelName: '申请单号：',
              codeField: 'claimOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true

            },
            {
              compKey: 'compKey3',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey9',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),

              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey6',
              labelName: '申请日期：',
              codeField: 'beginDate,endDate',
              component: () =>
                import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD HH:mm:ss',
              dataToObject: { timer: true, thirtyTime: true },
              // type: 'twoDatePicker',
              hhmmss: true, // 默认有时分秒
              format: 'yyyy-MM-dd',
              dateOptionsType: '0',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '关联单号：',
              codeField: 'purOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },


            {
              compKey: 'compKey10',
              labelName: '状态',
              codeField: 'claimStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '已保存' },
                { statusId: '1', statusText: '已提交' },
                { statusId: '2', statusText: '业务通过' },
                { statusId: '3', statusText: '业务驳回' },
                { statusId: '4', statusText: '已作废' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            }
            // {
            //   compKey: 'compKey11',
            //   span: 24,
            //   codeField: 'orderStatus',
            //   isMul: true,
            //   component: () => import('./orderStatus'),
            //   type: '',
            //   isMust: false
            // }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn',
              label: '操作',
              codeField: 'controlBtn',
              width: 150,
              align: 'center',
              isComponent: true,
              fixed: true,
              comps:
                  [
                    {
                      compKey: 'propKey1',
                      labelName: '修改',
                      codeField: 'editControlBtn',
                      clickEvent: (index) => {
                        this.edit(index)
                      },
                      component: () => import('@/components/org/linkButton'),
                      align: 'center'
                    },
                    {
                      compKey: 'propKey2',
                      labelName: '提交',
                      codeField: 'editControlBtn',
                      clickEvent: (index) => this.commit(index),
                      component: () => import('@/components/org/linkButton'),
                      align: 'center'
                    },
                    {
                      compKey: 'propKey3',
                      labelName: '作废',
                      codeField: 'editControlBtn',
                      clickEvent: (index) => this.toVoid(index),
                      component: () => import('@/components/org/linkButton'),
                      align: 'center'
                    },
                    {
                      compKey: 'propKey4',
                      labelName: '附件',
                      codeField: 'editControlBtn',
                      clickEvent: (index) => this.downLoad(index),
                      rowFileds: 'show:isAnnex-是',
                      component: () => import('@/components/org/linkButton'),
                      align: 'center'
                    }
                  ]
            },
            {
              prop: 'bigAreaId',
              label: '大区ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'claimOrderCode',
              label: '索赔申请单号'
              // isComponent: true,
              // comps: [
              //   {
              //     compKey: "propKey1",
              //     codeField: "claimOrderCode",
              //     component: () => import("@/components/org/linkButton"),
              //     clickEvent: (index) => this.edit(index),
              //   },
              // ],
            },
            {
              prop: 'claimOrderTypeCn',
              label: '索赔类型'
            },
            {
              prop: 'claimStatusCn',
              label: '状态'
            },
            {
              prop: 'claimDate',
              label: '申请日期'
            },
            {
              prop: 'claimAmount',
              label: '索赔总金额'
            },
            {
              prop: 'claimReason',
              label: '索赔原因'
            },
            {
              prop: 'inStoreCode',
              label: '关联单号'
            },
            {
              prop: 'isAnnex',
              label: '是否上传附件'
            }
          ],
      callbackObj: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
        },
        onCheckSelectChange: (selection) => {
          this.onCheckSelectChange1(selection)
        }
      },
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          claimOrderType: '',
          claimOrderCode: '',
          partNo: '',
          partName: '',
          beginDate: '',
          endDate: '',
          purOrderCode: '',
          claimStatus: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.orderStatus': {
      deep: true,
      handler: function(newV, oldV) {
        console.log('watch中：', newV)
        // this.querybystatus(newV)
        this.queryTable()
      }
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    a() {
      alert('1')
    },
    // 订单状态切换
    togglestatus() {
      if (this.status === true) {
        this.icon = 'el-icon-arrow-down'
        this.status = false
      } else {
        this.icon = 'el-icon-arrow-up'
        this.status = true
      }
      this.$refs.multipleTable.$refs.compKey11[0].curIsShow = this.status
      this.$refs.multipleTable.setTableHeight()
    },
    onCheckSelectChange1(selection) {
      var btn1 = this.tableButtons[2]
      var btn2 = this.tableButtons[3]
      var btn3 = this.tableButtons[4]
      var btn4 = this.tableButtons[5]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
      btn2.disabled = !isCheck
      btn3.disabled = !isCheck
      btn4.disabled = !isCheck
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData1 = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
    },

    add() {
      this.editPopupsState = 'add'
      this.editPopupsVisible = true
    },

    // 作废
    toVoid(index) {
      // alert('123')
      const data = this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
      console.log(data)
      this.toVoid1(data, orgApis.purchaseApplicationClaimToVoid)
    },
    // 提交
    commit(index) {
      const data = this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
      this.toVoid1(data, orgApis.purchaseApplicationClaimCommit)
    },
    // 作废
    toVoid1(data, obj) {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: obj,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: data

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg, /* 保存成功*/
            type: 'success',
            duration: 1000
          })

          this.queryTable(1)
        } else {
          // 保存失败
          this.$message({
            message:
             response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },

    // 附件
    downLoad(index) {
      const data = this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])

      // exportExcel({},data.annex,'')
      let arr = data.annex.split('/')
      const fileName = arr[arr.length - 1]
      this.$requestAPI({
        method: 'GET',
        apiUrl: data.annex,
        variables: {dataType: 'excel' }
      }).then(res => {
        // if (res.result === '1') {
        this.$utils.downloadFile(res, fileName)
        // } else {
        //   this.$message(res.msg ? res.msg : '')
        // }
      }).catch(err => {
        // if (err.response.data.msg) {
        //   this.$message(err.response.data.msg)
        // } else {
        //   this.$message(err.message)
        // }
        this.$message('附件下载失败!')
        console.log(err)
      })
    }

  }
}
</script>
<style lang='scss' scoped>
.red {
  background: red;
}
</style>
